/**
 * mongoclient: 封装mongodb处理
 * bushaofeng 2012.1.7
 */

#ifndef __MONGOCLIENT_H_
#define __MONGOCLIENT_H_

#include "mongo/client/dbclient.h"

using namespace mongo;

class MongoClient:public DBClientConnection{
    public:
        const static double MONGO_TIMEOUT = 3;
        MongoClient(){}
        MongoClient(const char* ip):DBClientConnection(true, 0, MONGO_TIMEOUT){
            connect(ip);
        }
        ~MongoClient(){}

        bool connect(const char* ip){
            try{
                DBClientConnection::connect(ip);
            }catch(DBException& e){
                return false;
            }
            fprintf(stdout, "Connect MongoDB OK.\n");
            return true;
        }

        BSONObj query(const string &ns, Query query=Query(), const BSONObj *fieldsToReturn = 0, int nToReturn = 0, int nToSkip = 0) {
            BSONArrayBuilder builder;

            auto_ptr<DBClientCursor> cursor = DBClientConnection::query(ns, query, nToReturn, nToSkip, fieldsToReturn, 0, 0);
            while(cursor->more()){
                BSONObj obj = cursor->next();
                builder.append(obj);
            }
            return builder.obj();
        }

        BSONObj findOneInArray(const string &ns, Query query=Query(), const BSONObj *fieldsToReturn = 0, int start= 0, int num= 0) {
            BSONArrayBuilder builder;
            BSONObj obj = findOne(ns, query, fieldsToReturn);
            if(num==0){
                return obj;
            }

            for(int i=0; i<num && i<obj.nFields(); i++){
                builder.append(obj[i]);
            }

            return obj;
        }
};

#endif
